<template>
  <div id="cluereport">
    <el-dialog
      title="错误详情"
      :visible.sync="dialogVisible"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <errorList :logId="logId" :timestamp="timestamp" />
    </el-dialog>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>人才建设</el-breadcrumb-item> -->
      <el-breadcrumb-item :to="{ path: '/zbbsmz/main' }">编制统计</el-breadcrumb-item>
      <el-breadcrumb-item>数据导入</el-breadcrumb-item>
    </el-breadcrumb>
    <section class="wboxs" style="height:110px">
    <!--工具条-->
      <h1>编制统计-数据导入</h1>
        <div style="padding:22px 22px 0;">
          <el-upload
            v-if="!processData||!processData.process"
            ref="upload"
            :action="$http.defaults.baseURL+$http.defaults.zbbsmzAPI +'api/xml/upload/'"
            :on-success="handleUploadSucc"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept="application/zip,application/x-zip,application/x-zip-compressed"
            :disabled="uploadLoading"
            v-loading="uploadLoading"
          >
            <el-button type="primary">导入数据</el-button>
          </el-upload>
          <div v-else>
            <el-progress :percentage="processData.process" :text-inside="true" :stroke-width="20"></el-progress>{{processData.message}}
          </div>
        </div>
    </section>
    <section class="wboxd" style="margin-top:10px">
      <!--列表-->
      <el-table :data="list" highlight-current-row v-loading="listLoading" style="width: 100%;" @sort-change='sortChange' :height="tableHeight" border
        ref="multipleTable"
        >
        <el-table-column type="index" label="序号" width="50" fixed align="center" class-name="tableth" :index="indexMethod">
        </el-table-column>
        <el-table-column prop="operateTime" label="操作时间" width="160" />
        <el-table-column prop="operateUser" label="操作用户" width="120" />
        <el-table-column prop="result" label="导入结果" width="130" />
        <el-table-column prop="fileName" label="zip文件名" width="350" />
        <el-table-column prop="importVersion" label="编制系统版本" width="110" />
        <el-table-column prop="remarks" label="备注" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.remarks }}{{ supportVersion(scope.row.importVersion) }}
          </template>
        </el-table-column>
        <el-table-column prop="isPrimary" label="是否主版本" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.isPrimary?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380">
          <template slot-scope="scope">
            <el-button @click="removeVersion(scope.row.id)" :loading="btnLoading" type="danger" size="mini" style="margin:10px 0 10px 5px">删除</el-button>
            <el-button v-if="!scope.row.isPrimary&&scope.row.result!=='失败'" :loading="btnLoading" @click="updatePrimary(scope.row.id)" type="primary" size="mini" style="margin:10px 0 10px 5px">设为主版本</el-button>
            <el-button v-if="scope.row.result==='成功但有错误'" @click="detail(scope.row.id)" size="mini" style="color:#000 !important;margin:10px 0 10px 5px">查看错误详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination style="float:right" :total="totalnum" :page-size="pageSize" @current-change="handleCurrentChange" :current-page="pageNum" @size-change="handleSizeChange" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      </div>
    </section>
  </div>
</template>

<script>
import errorList from './errorList'
export default {
  components: {
    errorList
  },
  data () {
    return {
      processData: null,
      connectserver: '',
      showconnect: false,
      connecttext: '',
      connectdisabled: false,
      mysocket: {},
      wsserverTimeoutObj: {},
      serverTimeoutObj: {},
      timeout: 180000, // 3分钟发一次心跳
      wstimeout: 3000, // 3分钟发一次心跳
      lockReconnect: false, // 是否真正建立连接
      timeoutnum: null, // 断开 重连倒计时
      wstimeoutObj: null,
      timeoutObj: null,
      btnLoading: false,
      uploadLoading: false,
      timestamp: '',
      listLoading: false,
      ids: [],
      tableHeight: 100,
      list: [
      ],
      pageNum: 1,
      pageSize: 20,
      totalnum: 10,
      logId: 0,
      dialogVisible: false,
      total: 0,
      Isace: 'asc',
      Sortkey: ''
    }
  },
  methods: {
    supportVersion (ver) {
      let supportVersion = localStorage.getItem('suppotVersion')
      if (ver > supportVersion) {
        return '系统当前仅支持到' + supportVersion + '版本，导入数据版本为' + ver + '，高于支持版本，数据统计可能不准确，请与管理员联系'
      }
    },
    handleUploadSucc (response) {
      this.uploadLoading = false
      console.log(response)
      if (response.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
      this.mysocket.close()
      this.processData = null
      this.getList()
    },
    uploadError (err) {
      this.uploadLoading = false
      this.mysocket.close()
      this.processData = null
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    beforeUpload (file) {
      this.openSocket()
      const isLt500M = file.size / 1024 / 1024 < 500
      const isFormat = file.name.indexOf('.zip') > 0
      if (!isLt500M) {
        this.$message.error('单个附件不能超过500M!')
      }
      if (!isFormat) {
        this.$message.error('数据包格式必须为zip!')
      }

      console.log('开始上传')
      if (isFormat && isLt500M) {
        this.uploadLoading = true
      }
      return isFormat && isLt500M
    },
    updatePrimary (id) {
      this.btnLoading = true
      this.$http
        .get(this.$http.defaults.zbbsmzAPI + 'api/xml/updatePrimary?version=' + id)
        .then(response => {
          this.btnLoading = false
          if (response.data.success) {
            this.$message({
              message: '设置成功！',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: '设置失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.btnLoading = false
          console.log(error)
          this.$message({
            message: '网络设置失败:' + error,
            type: 'error'
          })
        })
    },
    removeVersion (id) {
      this.$confirm('确认删除该版本全部数据吗?', '提示', {
        type: 'error'
      }).then(() => {
        this.btnLoading = true
        this.$http
          .get(this.$http.defaults.zbbsmzAPI + 'api/xml/removeVersion?version=' + id)
          .then(response => {
            this.btnLoading = false
            if (response.data.success) {
              this.$message({
                message: '删除成功！',
                type: 'success'
              })
              this.getList()
            } else {
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            this.btnLoading = false
            console.log(error)
            this.$message({
              message: '网络删除失败:' + error,
              type: 'error'
            })
          })
      }).catch(() => {
      })
    },
    indexMethod (index) {
      return index + (this.pageNum - 1) * this.pageSize + 1
    },
    formatDate (str) {
      return str.slice(0, 4) + '.' + str.slice(4, 6)
    },
    detail (id) {
      this.logId = id
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    handleSizeChange (val) {
      this.changeSizeFlag = true
      this.pageNum = 1
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      if (this.changeSizeFlag === false) {
        this.pageNum = val
        this.getList()
      }
    },
    // 排序
    sortChange: function (para) {
      if (para.order === 'ascending') {
        this.Isace = 'asc'
        this.Sortkey = para.prop
      } else if (para.order === 'descending') {
        this.Isace = 'desc'
        this.Sortkey = para.prop
      } else {
        this.Sortkey = null
        this.Isace = null
      }
      this.getList()
    },
    getList () {
      let para = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      this.listLoading = true
      this.$http
        .post(this.$http.defaults.zbbsmzAPI + `api/busLog/queryByPage`, para)
        .then(response => {
          if (response.data.success) {
            this.listLoading = false
            this.list = response.data.result.records
            this.totalnum = response.data.result.total
            this.totalPage = response.data.result.pages
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      let myheight = 315
      if (this.moreShow) {
        myheight = 377
      } else {
        myheight = 315
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - myheight
      })
    },
    openSocket () {
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持数据导入进度监控')
        this.showchart = false
        this.chartunshowtext = '您的浏览器不支持数据导入进度监控'
      } else {
        let _this = this
        this.showchart = true
        this.chartunshowtext = ''
        var socketUrl = this.$http.defaults.baseWsURL + 'api/websocket'
        console.log(socketUrl)
        this.mysocket = new WebSocket(socketUrl)
        // 打开事件
        this.mysocket.onopen = function () {
          _this.wsheartstart(true) // 心跳检测重置
          // _this.heartstart(true) // 心跳检测重置
          console.log('websocket已打开')
          _this.connectserver = '1'
          _this.showconnect = true
          _this.connecttext = '服务器连接成功'
          _this.connectdisabled = false
        }
        this.mysocket.onmessage = msg => {
          console.log('msg.data：' + msg.data)
          if (msg.data !== '连接成功') {
            this.processData = JSON.parse(msg.data)
            console.log('this.processData:')
            console.log(this.processData)
            if (this.processData.process === 100) {
              this.mysocket.close()
              this.processData = null
            }
          }
        }
        // 关闭事件
        this.mysocket.onclose = function () {
          console.log('websocket已关闭')
          _this.wsheartstart(false)
          // _this.heartstart(false)
          _this.connectserver = ''
          _this.showconnect = true
          _this.connecttext = '服务器连接断开'
          _this.connectdisabled = true
          // _this.reconnect()
        }
        // 发生了错误事件
        this.mysocket.onerror = function () {
          console.log('websocket发生了错误')
        }
      }
    },
    reconnect () { // 重新连接
      var that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        // 新连接
        that.openSocket()
        that.lockReconnect = false
      }, 5000)
    },
    wsheartstart (flag) {
      clearTimeout(this.wstimeoutObj)
      clearTimeout(this.wsserverTimeoutObj)
      if (!flag) {
        return
      }
      var self = this
      this.wstimeoutObj = setTimeout(function () {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        // onmessage拿到返回的心跳就说明连接正常
        console.log('hellows')
        self.mysocket.send('hellows')
        self.wsheartstart(true)
      }, self.wstimeout)
    },
    heartstart (flag) {
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      if (!flag) {
        return
      }
      var self = this
      this.timeoutObj = setTimeout(function () {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        // onmessage拿到返回的心跳就说明连接正常
        self.$http
          .get(`/api/prj/hello/`)
          .then(function (response) {
            console.log(response.data)
            self.heartstart(true)
          })
          .catch(function () {
            self.heartstart(true)
          })
      }, self.timeout)
    }
  },
  mounted () {
    // this.userRoles = localStorage.getItem('Roles')
    this.getList()
    this.tableresize(this)
    window.onresize = () => {
      this.tableresize(this)
    }
  }
}
</script>
<style>
#cluereport .el-drawer__wrapper{
  width: 100%;
  height: 100%;
  position: fixed !important;
  overflow: hidden;
}
  .wboxd .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .wboxd .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  .tableth{
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    height:33px;
  }
  #testlist .wboxs{
    height:45px;
    padding-top:10px;
  }
  #cluereport .el-table td{
    border-right: 1px solid #95B8E7;
    border-bottom: 1px solid #95B8E7;
  }
</style>
<style scoped>
  #cluereport .el-button{
    color:#fff !important;
  }
  #cluereport h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  .el-pagination{
    float: left;
    padding:7px 10px;
  }
  #cluereport .wboxs{
    width: 100%;
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
    padding:0;
  }
  .wboxd{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>
